package com.cxb.utils;

import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.os.PowerManager;
import android.os.StatFs;
import android.os.SystemClock;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.amitek.aidl.mqtt.bean.ConfigStatus;
import com.cxb.R;
import com.cxb.entity.Weather;
import com.cxb.manager.RootContext;
import com.cxb.service.CXBMainService;

public class CommonUtils {

	public static final int VERSION_ZHAOSHAN = 1;
	public static final int VERSION_AMI35C = 2;
	private OnRequestUpdateServerParam onRequestUpdateServerParam;

	/**
	 * 说明:精确到小数点后6位 Author:陈伟斌 2013-3-5
	 * 
	 * @param value
	 * @return
	 */
	public static String round(double value) {
		DecimalFormat format = new DecimalFormat("#0.000000");
		return format.format(value);
	}

	public static String roundTwo(double value) {
		DecimalFormat format = new DecimalFormat("#0.00");
		return format.format(value);
	}

	public static String date2Str(Date date, String splitStr) {

		if (splitStr == null) {
			splitStr = "-";
		}
		SimpleDateFormat df = new SimpleDateFormat("yyyy" + splitStr + "MM"
				+ splitStr + "dd");
		return df.format(date);
	}

	public static boolean isSDExists(Context context) {

		long availableMemorySize = 0;

		long sdcard1 = getAvailableMemorySize("/mnt/sdcard/");
		long sdcard2 = getAvailableMemorySize("/mnt/sdcard2/");

		return sdcard1 > 0 && sdcard2 > 0;

	}

	public static boolean isInnerMemoryExists(Context context) {

		long sdcard1 = getAvailableMemorySize("/mnt/sdcard/");

		return sdcard1 > 0;

	}

	public static boolean isExternalStorageAvailable() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}

	public static long getAvailableMemorySize(String volumn) {
		// String sdcard2 = "/mnt/sdcard2/";
		if (isExternalStorageAvailable()) {
			// File path =
			// Environment.getExternalStorageDirectory();//获取SDCard根目录
			StatFs stat = new StatFs(volumn);
			long blockSize = stat.getBlockSize();
			long availableBlocks = stat.getBlockCount();
			// long availableBlocks = stat.getAvailableBlocks();
			return availableBlocks * blockSize;
		} else {
			return -1;
		}
	}

	/**
	 * @Title: isMobileNO
	 * @Description: 判断是不是手机号码
	 * @param @param mobiles
	 * @param @return 设定文件
	 * @return boolean 返回类型
	 * @throws
	 */
	public static boolean isMobileNO(String mobiles) {

		Pattern p = Pattern
				.compile("^((14[0-9])|(17[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");

		Matcher m = p.matcher(mobiles);

		System.out.println(m.matches() + "---");

		return m.matches();

	}

	public static boolean isTelephone(String phonenumber) {
		String phone = "0\\d{2,3}\\d{3,8}";
		Pattern p = Pattern.compile(phone);
		Matcher m = p.matcher(phonenumber);
		if (m.matches()) {
			return true;
		}
		return false;
	}

	public static String getSystemProperties(String field)// ȡϵͳ����
	{
		String platform = null;
		try {
			Class<?> classType = Class.forName("android.os.SystemProperties");
			Method getMethod = classType.getDeclaredMethod("get",
					new Class<?>[] { String.class });
			platform = (String) getMethod.invoke(classType,
					new Object[] { field });
		} catch (Exception e) {
			e.printStackTrace();
		}
		return platform;
	}

	public static void setSystemProperties(String field, String value)// ȡϵͳ����
	{
		RootContext.getInstance().runCommand("setprop " + field + " " + value);

	}

	public static String getInnerVersionName() {
		
	
		String innerVersion = getSystemProperties("cxb.mobile.version");
		if (!TextUtils.isEmpty(innerVersion)) {
			return innerVersion.replace("35SB", "35S8");
		}
		return "";
	}

	public static boolean isServiceRunning(Context mContext, String className) {
		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager
				.getRunningServices(30);
		if (!(serviceList.size() > 0)) {
			return false;
		}
		for (int i = 0; i < serviceList.size(); i++) {
			if (serviceList.get(i).service.getClassName().equals(className) == true) {
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}

	public static String getModel() {
		String model = getSystemProperties("cxb.model");
		return model;

	}

	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm == null) {
		} else {

			NetworkInfo[] info = cm.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	public static void setMobileData(Context context, boolean enable) {

		TelephonyManager telephonyManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		try {
			Method setDataEnabled = telephonyManager.getClass().getMethod(
					"setDataEnabled", boolean.class);
			setDataEnabled.invoke(telephonyManager, enable);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("移动数据设置错误: " + e.toString());
		}
	}

	public static void switch3GMode(Context mContext) {

		mContext.sendBroadcast(new Intent("ACTION_AMI_RESTART_3G_MODE"));
	}

	public static String getRunningActivityName(Context context) {
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		String runningActivity = activityManager.getRunningTasks(1).get(0).topActivity
				.getClassName();
		return runningActivity;
	}

	/**
	 * 判断是否打开USB存储
	 * 
	 * @return
	 */
	public static boolean isUSBMass() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_SHARED);
	}

	public static void wakeUpScreen(Context context) {
		PowerManager powerManager = (PowerManager) context
				.getSystemService(Context.POWER_SERVICE);
		Method method;

		try {
			method = powerManager.getClass().getMethod("wakeUp", long.class);
			method.setAccessible(true);
			method.invoke(powerManager, SystemClock.uptimeMillis());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void shutdown(Context context) {

		Debug.printfLog("shutdown");
		RootContext.getInstance().runCommand("reboot -p");
	}

	public static Weather getWeatherByString(String json, Context context) {
		Log.d("pumkid", json);
		Weather mWeather = new Weather();
		try {
			JSONObject jsonObject = new JSONObject(json);
			if (jsonObject.has("update_time")) {
				mWeather.setUpdate_time(jsonObject.getString("update_time"));
			}
			if (jsonObject.has("aqi")) {
				JSONObject jsonaqi = jsonObject.getJSONObject("aqi");
				if (jsonaqi.has("pm25")) {
					mWeather.setPm25(jsonaqi.getString("pm25"));
					if (TextUtils.isDigitsOnly(mWeather.getPm25())) {
						int pm = Integer.parseInt(mWeather.getPm25());
						if (pm <= 35)
							mWeather.setQlty(context
									.getString(R.string.pm25best));
						else if (pm > 35 && pm <= 75)
							mWeather.setQlty(context
									.getString(R.string.pm25good));
						else if (pm > 75 && pm <= 115)
							mWeather.setQlty(context
									.getString(R.string.pm25littlep));
						else if (pm > 115 && pm <= 150)
							mWeather.setQlty(context
									.getString(R.string.pm25worse));
						else if (pm > 150 && pm <= 250)
							mWeather.setQlty(context
									.getString(R.string.pm25worsethanworse));
						else if (pm > 250)
							mWeather.setQlty(context
									.getString(R.string.pm25severity));
					}
				}

			}
			if (jsonObject.has("district")) {
				mWeather.setDistrict(jsonObject.getString("district"));
			}
			if (jsonObject.has("city")) {

				mWeather.setCity(jsonObject.getString("city"));
			}
			if (jsonObject.has("daily_forecast")) {
				try {
					JSONArray daily_forecastjson = jsonObject
							.getJSONArray("daily_forecast");
					if (daily_forecastjson.length() > 1) {
						JSONObject jw = daily_forecastjson.getJSONObject(0);
						if (jw.has("date")) {
						}
						if (jw.has("cond")) {
							JSONObject jcond = jw.getJSONObject("cond");
							if (jcond.has("code_d")) {
								mWeather.setCode_d(jcond.getString("code_d"));
							}
							if (jcond.has("code_n")) {
								mWeather.setCode_n(jcond.getString("code_n"));
							}
							if (jcond.has("txt_d")) {
								mWeather.setTxt_d(jcond.getString("txt_d"));
							}
							if (jcond.has("txt_n")) {
								mWeather.setTxt_n(jcond.getString("txt_n"));
							}
						}
						if (jw.has("tmp")) {
							JSONObject jtmp = jw.getJSONObject("tmp");
							if (jtmp.has("max")) {
								mWeather.setTmpMax(jtmp.getString("max"));
							}
							if (jtmp.has("min")) {
								mWeather.setTmpMin(jtmp.getString("min"));
							}
						}
						if (jw.has("wind")) {
							JSONObject jwind = jw.getJSONObject("wind");
							if (jwind.has("deg")) {
								mWeather.setWindDeg(jwind.getString("deg"));
							}
							if (jwind.has("dir")) {
								mWeather.setWindDir(jwind.getString("dir"));
							}
							if (jwind.has("sc")) {
								mWeather.setWindSc(jwind.getString("dir"));
							}
							if (jwind.has("spd")) {
								mWeather.setWindspd(jwind.getString("spd"));
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return mWeather;
	}

	private static final double EARTH_RADIUS = 6378137.0;

	public static double getDistance(double longitude1, double latitude1,
			double longitude2, double latitude2) {
		double Lat1 = rad(latitude1);
		double Lat2 = rad(latitude2);
		double a = Lat1 - Lat2;
		double b = rad(longitude1) - rad(longitude2);
		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
				+ Math.cos(Lat1) * Math.cos(Lat2)
				* Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000;
		return s;
	}

	private static double rad(double d) {
		return d * Math.PI / 180.0;
	}

	interface OnRequestUpdateServerParam {
		public void doNoNetwork();
	}

	public static boolean isAppInstall(Context context, String packageName) {
		final PackageManager packageManager = context.getPackageManager();
		// 获取所有已安装程序的包信息
		List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
		for (int i = 0; i < pinfo.size(); i++) {
			if (pinfo.get(i).packageName.equalsIgnoreCase(packageName))
				return true;
		}
		return false;
	}
	
	public static  boolean isWeixinBind() {

		try {
			ConfigStatus configStatus = CXBMainService.getMqttProxy()
					.getConfigStatus();
			return configStatus.bindStatus != null
					&& configStatus.bindStatus.bindStatus;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
}
